/** @package:com.yxw.ui
 *	@author: Administrator
 *	@date: 2018年11月30日上午10:31:26
 */
package com.yxw.ui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;

import com.yxw.serialportutil.ReadSerialPort;
import com.yxw.serialportutil.SerialPortUtil;
import com.yxw.serialportutil.SerialPortUtil.SerialPortListener;

import gnu.io.PortInUseException;
import gnu.io.SerialPort;

/** @Classname:ClickActionUtil
 *	@Description:TODO
 *	@author: Administrator
 *	@date: 2018年11月30日上午10:31:26
 */
public class ClickActionUtil {
	
	private SerialPort serialPort;
	private JTextArea jta_rm;     //信息接收区域
	private JTextArea jta_sma;   //信息发送区域
	private JLabel sendAccountLable; 
	private JLabel reciveAccountLable;
	private JComboBox<String> JComboBox_reciveDataType;
	
	
	public SerialPort getSerialPort() {
		return serialPort;
	}

	public void setSerialPort(SerialPort serialPort) {
		this.serialPort = serialPort;
	}
	
	public JComboBox<String> getJComboBox_reciveDataType() {
		return JComboBox_reciveDataType;
	}

	public void setJComboBox_reciveDataType(JComboBox<String> jComboBox_reciveDataType) {
		JComboBox_reciveDataType = jComboBox_reciveDataType;
	}

	public JLabel getSendAccountLable() {
		return sendAccountLable;
	}

	public void setSendAccountLable(JLabel sendAccountLable) {
		this.sendAccountLable = sendAccountLable;
	}

	public JLabel getReciveAccountLable() {
		return reciveAccountLable;
	}

	public void setReciveAccountLable(JLabel reciveAccountLable) {
		this.reciveAccountLable = reciveAccountLable;
	}

	public JTextArea getJta_rm() {
		return jta_rm;
	}

	public void setJta_rm(JTextArea jta_rm) {
		this.jta_rm = jta_rm;
	}

	public JTextArea getJta_sma() {
		return jta_sma;
	}

	public void setJta_sma(JTextArea jta_sma) {
		this.jta_sma = jta_sma;
	}

	/*
	 * params :openPortButton,JComboBox_port,JComboBox_btl,JComboBox_jyw,JComboBox_sjw,JComboBox_tzw
	 *打开串口的点击事件
	 */
	public SerialPort openPortAction(JButton openPortButton,JButton closePortButton,JComboBox<?> JComboBox_port,JComboBox<?> JComboBox_btl,JComboBox<?> JComboBox_jyw,
			JComboBox<?> JComboBox_sjw,JComboBox<?> JComboBox_tzw,
			 JCheckBox ASCIICheckbox,JCheckBox checkDataCheckbox,JCheckBox timeCheckbox,
			 JCheckBox addLineEndCheckbox,JComboBox<String> JComboBox_sendDataType
			){
		boolean opensign = true;
		openPortButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub 获取端口名称与波特率
				openPortButton.setEnabled(false);
				closePortButton.setEnabled(true);
				
				String portName = (String) JComboBox_port.getSelectedItem();
				JComboBox_port.setEnabled(false);
				
				String Btl = (String) JComboBox_btl.getSelectedItem();
				JComboBox_btl.setEnabled(false);
				
				String Jyw = (String) JComboBox_jyw.getSelectedItem();
				JComboBox_jyw.setEnabled(false);
				
				String sjw = (String) JComboBox_sjw.getSelectedItem();
				JComboBox_sjw.setEnabled(false);
				
				String tzw = (String) JComboBox_tzw.getSelectedItem();
				JComboBox_tzw.setEnabled(false);
				
				System.out.println(portName+" "+Btl+" "+Jyw+" "+sjw+" "+tzw);
				SerialPortUtil spu = new SerialPortUtil();
				try {
					//SerialPort serialPort = 
					//打开串口
					serialPort = SerialPortUtil.openPort(portName, Integer.parseInt(Btl), Jyw, sjw, tzw);
					//开启监听
					//serialPort.addEventListener(SerialPortListener.class);
					
					//SerialPortUtil.addListener(serialPort, SerialPortUtil.);
					
					ReadSerialPort rsp = new ReadSerialPort();
					rsp.setSerialPort(serialPort);
					rsp.selectPort(portName);
					//rsp.setCommPort();
					//需要向目标线程传送textarea对象
					rsp.setJta_rm(jta_rm);
					rsp.setAddLineEndCheckbox(addLineEndCheckbox);
					rsp.setASCIICheckbox(ASCIICheckbox);
					rsp.setCheckDataCheckbox(checkDataCheckbox);
					rsp.setTimeCheckbox(timeCheckbox);
					rsp.setJComboBox_sendDataType(JComboBox_sendDataType);
					rsp.setReciveAccountLable(reciveAccountLable);
					rsp.setSendAccountLable(sendAccountLable);
					rsp.startRead();
					
					System.out.println();
					
					String rec = new String(SerialPortUtil.readFromPort(serialPort));
					System.out.println(rec);
				} catch (PortInUseException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				System.out.println("---");
			}
		});
		return serialPort;
	}
	
	/*
	 * 关闭串口的按钮点击事件
	 * params同打开串口
	 */
	public boolean closePortAction(JButton openPortButton,JButton closePortButton,JComboBox<?> JComboBox_port,JComboBox<?> JComboBox_btl,JComboBox<?> JComboBox_jyw,
			JComboBox<?> JComboBox_sjw,JComboBox<?> JComboBox_tzw){
		boolean closesign = true;
		closePortButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				openPortButton.setEnabled(true);
				closePortButton.setEnabled(false);
				
				String portName = (String) JComboBox_port.getSelectedItem();
				
				JComboBox_port.setEnabled(true);
				JComboBox_btl.setEnabled(true);
				JComboBox_jyw.setEnabled(true);
				JComboBox_sjw.setEnabled(true);
				JComboBox_tzw.setEnabled(true);
				SerialPortUtil.closePort(serialPort);
				
				System.out.println(portName+" ");
			}
		});
		return closesign;
	}
	
	
	//手动发送
	public boolean senfMeaasgeAction(JButton sendMessageButton,JTextArea jta_sma,JComboBox JComboBox_port,
			JCheckBox ASCIICheckbox,JCheckBox checkDataCheckbox,JCheckBox timeCheckbox,JCheckBox ClearCheckbox,
			JCheckBox addLineEndCheckbox,JCheckBox showSendCheckbox,
			JComboBox<String> JComboBox_sendDataType,JCheckBox loopTestCheckbox,JTextField jtf_loopTime
			//JCheckBox ASCIICheckbox = CreateJCheckBox("ASCII");
			//JCheckBox HexCheckbox = CreateJCheckBox("校验解析");
			//JCheckBox timeCheckbox = CreateJCheckBox("时间戳");
			//JCheckBox ClearCheckbox = CreateJCheckBox("自动清空");
			//JCheckBox addLineEndCheckbox = CreateJCheckBox("自动换行");
			//JCheckBox showSendCheckbox = CreateJCheckBox("显示发送");
			){
		
		sendMessageButton.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				String portName = (String) JComboBox_port.getSelectedItem();
				//JComboBox_port.setEnabled(false);     ???
				
				//final String message="";
				
				String message = jta_sma.getText();
				ReadSerialPort rsp = new ReadSerialPort();
				rsp.setSerialPort(serialPort);
				rsp.selectPort(portName);
				rsp.setReciveAccountLable(reciveAccountLable);
				rsp.setSendAccountLable(sendAccountLable);
				//rsp.setCommPort();
				//需要向目标线程传送textarea对象
				//发送之前，判断单选与复选框的状态
					String selectItem = (String) JComboBox_reciveDataType.getSelectedItem();
					switch (selectItem){
						case "二进制":message = toBinary(message);break;
						case "八进制":message = toOctal(message);break;
						case "十六进制":message = hex2byte(message);break;
					}
				//发送
				rsp.setJta_rm(jta_rm);
				if(!loopTestCheckbox.isSelected()){
					rsp.write(message);
				}

				if(timeCheckbox.isSelected()){
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					message = "[" + df.format(new Date()) + "]" + message;
				}
				
				if(ClearCheckbox.isSelected()){
					jta_sma.setText("");
				}
				
				if(addLineEndCheckbox.isSelected()){
					//String tmp = jta_rm.getText();
					//jta_rm.setText(tmp+"\n");
					message = "\n" + message;
				}
				
				if(showSendCheckbox.isSelected()){
					String tmp = jta_rm.getText();
					jta_rm.setText(tmp+message);
				}
			}
			
		});
		return true;
	}
	
	public boolean clearReaciveArea(JButton clearReaciveAreaButton,JTextArea jta_rm){
		clearReaciveAreaButton.addActionListener(new ActionListener(){
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				sendAccountLable.setText("0");; 
				reciveAccountLable.setText("0");;
				
				jta_rm.setText("");
			}
			
		});
		return true;
	}
	
	public boolean ASCIICheckBox(JCheckBox ASCIICheckbox,JComboBox<String> JComboBox_sendDataType){
		ASCIICheckbox.addItemListener(new ItemListener(){
			@Override
			public void itemStateChanged(ItemEvent e) {
				// TODO Auto-generated method stub
				if(ASCIICheckbox.isSelected()){
					JComboBox_sendDataType.setEnabled(false);
				}else{
					JComboBox_sendDataType.setEnabled(true);
				}
			}
			
		});
		
		return true;
	}
	
	
	//自动发送
	public boolean loopSendMessage(JCheckBox loopTestCheckbox,JTextField jtf_loopTime,JComboBox JComboBox_port
			,JCheckBox ASCIICheckbox,JCheckBox checkDataCheckbox,JCheckBox timeCheckbox,JCheckBox ClearCheckbox,
			JCheckBox addLineEndCheckbox,JCheckBox showSendCheckbox
			){
		//private JTextArea jta_rm;     //信息接收区域
		//private JTextArea jta_sma;   //信息发送区域
		
		loopTestCheckbox.addItemListener(new ItemListener() {
			@Override
			public void itemStateChanged(ItemEvent e) {
				
				new Thread(new Runnable() {  
	                public void run() {  
	                	System.out.println("run");
	                	while(loopTestCheckbox.isSelected()){  
	                		System.out.println("loop");
		            		ReadSerialPort rsp = new ReadSerialPort();
		            		String portName = (String) JComboBox_port.getSelectedItem();
		                	String message = jta_sma.getText();
							rsp.setSerialPort(serialPort);
							rsp.selectPort(portName);
							//发送
								String selectItem = (String) JComboBox_reciveDataType.getSelectedItem();
								switch (selectItem){
									case "二进制":message = toBinary(message);break;
									case "八进制":message = toOctal(message);break;
									case "十六进制":message = hex2byte(message);break;
								}
							rsp.setReciveAccountLable(reciveAccountLable);
							rsp.setSendAccountLable(sendAccountLable);
							rsp.setJta_rm(jta_rm);
							rsp.write(message);

							try {
								Thread.sleep(Integer.valueOf(jtf_loopTime.getText()));
							} catch (NumberFormatException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
	                        SwingUtilities.invokeLater(new Runnable() {  
	                            public void run() {  
	                            	System.out.println("SwingUtilitiesinvokeLaterloop");
	                                //button.setText(i+"");
	                            	String tmp = "";
	                            	String message = jta_sma.getText();
	                            	String selectItem = (String) JComboBox_reciveDataType.getSelectedItem();
									switch (selectItem){
										case "二进制":message = toBinary(message);break;
										case "八进制":message = toOctal(message);break;
										case "十六进制":message = hex2byte(message);break;
									}
	                            	if(timeCheckbox.isSelected()){
	    								SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    								message = "[" + df.format(new Date()) + "]" + message;
	    							}
	    							
	    							if(ClearCheckbox.isSelected()){
	    								jta_sma.setText("");
	    							}
	    							
	    							if(addLineEndCheckbox.isSelected()){
	    								//tmp = jta_rm.getText();
	    								//jta_rm.setText(tmp+"\n");
	    								message = "\n" + message;
	    							}
	    							
	    							if(showSendCheckbox.isSelected()){
	    								tmp = jta_rm.getText();
	    								jta_rm.setText(tmp+message);
	    							}
	                                //jta_rm.setText(tmp+message);
	                            }  
	                        });  
	                    }  
	                }  
	            }).start();
			}
			
		});
		return true;
	}
	public String hex2byte(String s) {

	        //String digital = "0123456789ABCDEF";
	        //String hex1 = s.replace(" ", "");
	        //char[] hex2char = hex1.toCharArray();
	       // byte[] bytes = new byte[hex1.length() / 2];
	        //byte temp;
	        //for (int p = 0; p < bytes.length; p++) {
	        //    temp = (byte) (digital.indexOf(hex2char[2 * p]) * 16);
	        //    temp += digital.indexOf(hex2char[2 * p + 1]);
	        //    bytes[p] = (byte) (temp & 0xff);
	        //}
	        //String s = "";
	        //for(int j = 0;j < bytes.length;j++){
	        //    s += new String(String.valueOf(bytes[j])).trim();
	        //}
		 	String str = "";
		    for (int i = 0; i < s.length(); i++) {
		       int ch = (int) s.charAt(i);
		        String s4 = Integer.toHexString(s.charAt(i) - '0');
		        str = str + s4;
		    }
		    return str;
	        //return s;
	    }
	    
	    //二进制转换
	    public String toBinary(String str){
	        char[] strChar=str.toCharArray();
	        String result="";
	        System.out.println(strChar.length);
	        for(int i=0;i<strChar.length;i++){
	        	System.out.println(strChar[i]);
	        	System.out.println("---"+Integer.toBinaryString(strChar[i]));
	            result +=Integer.toBinaryString(strChar[i] - '0')+ " ";
	        }
	        //System.out.println(result);
	        return result;
	    }
	    
	    //8进制转换
	    public String toOctal(String str){
		    //String bin = toBinary(str);
		    String result="";
		    char[] strChar=str.toCharArray();
		    
		    for(int i=0;i<strChar.length;i++){
		        result +=Integer.toOctalString(strChar[i] - '0')+ " ";
		    }
		    System.out.println(result);
		    return result;
	    }
}
